The IF Statement
The IF statement allows us to execute some statement or block of code
only if the result of the conditional expression is true.
Each conditional expression is evaluated to .TRUE.
or .FALSE.
and the code is executed if the results is true
Relational Operators
FORTRAN | MATLAB | English |
---|---|---|
.EQ. | == | equal to |
.NE. | ~= | not equal to |
.LT. | < | less than |
.LE. | <= | less than or equal |
.GT. | > | greater than |
.GE. | >= | greater than or equal |
Logical Operators
FORTRAN | MATLAB | English |
---|---|---|
.NOT. | ~ | True only if the operand is true |
.AND. | & | True only if both operands are true |
.OR. | | | True if either operands are true |
IF and IF-ENDIF
If there is only one short statement to execute, use the single line
form of the IF
statement.
IF (newval .LT. minval) minval = newval
If there is more than one or a longer statement to execute, use the block
form of the IF
statement.
IF (gradepercent >= 93) THEN lettergrade = 'A' Astudents = Astudents + 1 ENDIF
IF-ELSE-ENDIF
Include an ELSE
clause in your IF
statement
to provide an alternative code block to execute if the condition is false.
IF (numscores > 0) THEN CALL computeAverage ELSE write (*,*) 'No scores to average' ENDIF
IF-ELSEIF-ELSE-ENDIF
IF (x .EQ. 0) THEN WRITE(*,*) 'x equals 0' ELSEIF (x .GT. 0) THEN IF (x .LT. y) THEN WRITE(*,*) 'x > 0 and x < y' ELSE WRITE(*,*) 'x > 0 and x >= y' ENDIF ELSE IF (x .LT. y) THEN WRITE(*,*) 'x <= 0 and x < y' ELSE WRITE(*,*) 'x <= 0 and x >= y' ENDIF ENDIF
General Form
The words IF
, THEN
, ELSEIF
, ELSE
and ENDIF
are reserved words,
The general form of an IF
statement in FORTRAN is:
IF (condition) THEN statement(s) ELSEIF (condition) THEN statement(s) ELSEIF (condition) THEN statement(s) [more elseif conditions and blocks here] ELSE statement(s) ENDIF
where:
condition is a boolean expression and
statements is one or more FORTRAN command statements
that we want to execute if the condition evaluates to true.